// pages/order/list.js
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,

        title_list: [{ name: "全部", num: 0 }, { name: "待付款", num: 0 }, { name: "待发货", num: 0 }, { name: "待收货", num: 0 }, { name: "待评价", num: 0 }, { name: "退款/售后", num: 0 }],
        chosen_index: 0,
        all_list: [],
        waitPay_list: [],
        waitDeliver_list: [],
        waitReceive_list: [],
        waitComment_list: [],
        service_list: [],


        loading_text: "暂无数据",
        uid: '',
        status: '0',
        order_status_number: [0, 1, 2, 3, 4],
        order_status: ['', '待付款', '待发货', '已取消', '已作废', '待评价', '已退款', '部分退款', '售后中', '换货成功', '已过期'],
        isDeliver: ['待发货', '待收货'],
        winHeight: '',
        styledata: {
            "bg_color": "white",
            "color": "#000",
            "leftflag": true,
            "homeflag": true,
            "name": "我的订单"
        },

        noseeShow: false,
        currentList: '',

        limit: 6,
        allpage: 0,
        waitPpage: 0,
        waitDpage: 0,
        waitRpage: 0,
        waitCpage: 0,
        waitSpage: 0,


        nomoreall: false,
        nomorep: false,
        nomored: false,
        nomorer: false,
        nomorec: false,
        nomores: false,

        // 是否为下拉刷新调用
        ispullrefresh: false,
        // 下拉刷新
        allpull: false,
        ppull: false,
        dpull: false,
        rpull: false,
        cpull: false,
        spull: false,


    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            uid: App.globalData.uid,
            chosen_index: options.index,
            status: options.status,
        })


        let that = this
        wx.getSystemInfo({
            success: function (res) {
                var clientHeight = res.windowHeight,
                    clientWidth = res.windowWidth,
                    rpxR = 750 / clientWidth;
                var calc = clientHeight * rpxR + 100;
                that.setData({
                    winHeight: calc,
                });
                //console.log(that.data.winHeight);
            }
        });

        if (options.status == '0') {
            this.getOrderList()
        }
    },

    // 查看物流
    checkdelivery(e) {
        let oid = e.currentTarget.dataset.oid
        let mobile = e.currentTarget.dataset.mobile

        wx.navigateTo({
            url: `/pages/order/deliveryInfo?oid=${oid}&mobile=${mobile}`
        })
    },

    // 评论按钮回调
    goComment() {
        util.showToast('感谢您的反馈，该功能正加速升级中')
        return
    },

    // 确认收货按钮回调
    confirmReceived(e) {
        const that = this
        let id = e.currentTarget.dataset.id
        let index = e.currentTarget.dataset.index
        let whichReceive = `${this.data.currentList}[${index}].isReceived`

        wx.showModal({
            title: '提示',
            content: '是否确认已收到商品',
            showCancel: true,
            confirmText: '确认',
            success: async (res) => {
                if (res.confirm) {
                    let res = await request.post(api.orderconfirmReceive, { id })
                    // console.log(res);
                    if (res == 1) {
                        util.showToast('您已确认收货')
                        this.setData({
                            [whichReceive]: true
                        })
                    }
                } else if (res.cancel) {
                    util.showToast('已取消')
                }
            },
            fail: () => {
                util.showToast('操作失败请重试')
            }
        })
    },

    // 订单删除
    deleteOrder(e) {
        const that = this
        let id = e.currentTarget.dataset.id
        let index = e.currentTarget.dataset.index
        let status = e.currentTarget.dataset.status
        // 判断是否可删除
        if (status == 3 || status == 10) {
            wx.showModal({
                title: '提示',
                content: '是否删除该订单',
                showCancel: true,
                confirmText: '确认删除',
                success: async (res) => {
                    if (res.confirm) {
                        let res = await request.post(api.orderdel, { uid: this.data.uid, ids: id })
                        // console.log(res);
                        that.reloadOrderList(index, true)
                    } else if (res.cancel) {
                        util.showToast('已取消')
                    }
                },
                fail: () => {
                    util.showToast('操作失败请重试')
                }
            })
            return
        } else {
            util.showToast('订单当前状态不可删除')
            return
        }

        // console.log(id);
    },

    // 订单取消
    deleteCancel(e) {
        const that = this
        let id = e.currentTarget.dataset.id
        let index = e.currentTarget.dataset.index
        // console.log(id);
        wx.showModal({
            title: '提示',
            content: '是否取消该订单',
            showCancel: true,
            confirmText: '确认取消',
            success: async (res) => {
                if (res.confirm) {
                    let res = await request.post(api.orderstatus, { status: 3, id })
                    // console.log(res);
                    that.reloadOrderList(index)

                } else if (res.cancel) {
                    util.showToast('已取消操作')
                }
            },
            fail: () => {
                util.showToast('操作失败请重试')
            }
        })
    },

    // 下拉刷新
    pullRefresh1(e) {
        this.setData({
            allpage: 0,
            nomoreall: false,
            ispullrefresh: true
        })

        setTimeout(async () => {
            let flag = await this.getOrderList()
            if (flag) {
                this.setData({
                    allpull: false,
                    ispullrefresh: false
                })
            }
        }, 1500);
    },

    // 待支付下拉刷新
    pullRefresh2(e) {
        this.setData({
            waitPpage: 0,
            nomorep: false,
            ispullrefresh: true
        })

        setTimeout(async () => {
            let flag = await this.getOrderList()
            if (flag) {
                this.setData({
                    ppull: false,
                    ispullrefresh: false
                })
            }
        }, 1500);
    },
    // 待发货下拉刷新
    pullRefresh3(e) {
        this.setData({
            waitDpage: 0,
            nomored: false,
            ispullrefresh: true
        })

        setTimeout(async () => {
            let flag = await this.getOrderList(true)
            if (flag) {
                this.setData({
                    dpull: false,
                    ispullrefresh: false
                })
            }
        }, 1500);
    },
    // 待收货下拉刷新
    pullRefresh4(e) {
        this.setData({
            waitRpage: 0,
            nomorer: false,
            ispullrefresh: true
        })

        setTimeout(async () => {
            let flag = await this.getOrderList()
            if (flag) {
                this.setData({
                    rpull: false,
                    ispullrefresh: false
                })
            }
        }, 1500);
    },
    // 待评价下拉刷新
    pullRefresh5(e) {
        this.setData({
            waitCpage: 0,
            nomorec: false,
            ispullrefresh: true
        })

        setTimeout(async () => {
            let flag = await this.getOrderList()
            if (flag) {
                this.setData({
                    cpull: false,
                    ispullrefresh: false
                })
            }
        }, 1500);
    },
    // 售后下拉刷新
    pullRefresh6(e) {
        this.setData({
            waitSpage: 0,
            nomores: false,
            ispullrefresh: true
        })

        setTimeout(async () => {
            let flag = await this.getOrderList()
            if (flag) {
                this.setData({
                    spull: false,
                    ispullrefresh: false
                })
            }
        }, 1500);
    },

    // 点击遮罩层隐藏弹出框
    tapNoSeemask() {
        let index = this.data.currentIndex
        let str = (index === undefined || index === '') ? 'firstindex' : `${this.data.currentList}[${index}].showMore`
        this.setData({
            [str]: false,
            noseeShow: false
        })
    },

    // 点击弹出更多
    showMore(e) {
        // 弹出点击的更多弹出框
        let index = e.currentTarget.dataset.index
        let currentList = this.data.currentList
        let str = `${currentList}[${index}].showMore`

        // 关闭上一个更多弹出框     
        let lastindex = this.data.currentIndex
        let laststr = (lastindex === undefined || lastindex === '') ? 'firstindex' : `${currentList}[${lastindex}].showMore`

        this.setData({
            [laststr]: false,
            [str]: true,
            currentIndex: index,
            noseeShow: true
        })
    },

    // 订单列表局部更新
    async reloadOrderList(index, isdel = false) {
        util.showLoading('正在更新')

        // 计算局部更新的页数
        let pagenum = parseInt(index / this.data.limit + 1)

        // 如果后面做上拉加载 whichlist变量就需要加到data中保存
        // 选择对应的数组
        let whichList
        let nomoreflag

        switch (this.data.status) {
            case '0':
                whichList = 'all_list';
                nomoreflag = 'nomoreall'
                break;
            case '1':
                whichList = 'waitPay_list';
                nomoreflag = 'nomorep'
                break;
            case '2':
                whichList = 'waitDeliver_list';
                nomoreflag = 'nomored'
                break;
            case '3':
                whichList = 'waitReceive_list';
                nomoreflag = 'nomorer'
                break;
            case '4':
                whichList = 'waitComment_list';
                nomoreflag = 'nomorec'
                break;
            case '5':
                whichList = 'service_list';
                nomoreflag = 'nomores'
                break;
            default:
                break;
        }

        // 直接隐藏透明框
        this.tapNoSeemask()

        // 如果是订单删除操作，则更新少一个
        let limitnum = isdel ? this.data.limit - 1 : this.data.limit
        let params = {
            uid: this.data.uid,
            status: this.data.status,
            page: pagenum,
            limit: limitnum
        }

        let list = this.data[whichList]
        let res = await request.post(api.orderlist, params)

        // 如果是退款/售后 判断是否已退款，有展示对应退款金额
        if (whichList == 'service_list' || whichList == 'all_list') {
            for (let i = 0; i < res.length; i++) {
                if (res[i].status == 6 || res[i].status == 7) {
                    let RMresult = await request.postall(api.RMdetail, { oid: res[i].id })
                    if (RMresult.code == 0 && RMresult.data.pay_status == 2) {
                        res[i].RMamount = RMresult.data.amount
                    }
                }

            }
        }

        if (res.length == 0) {
            // 如果列表只有一条记录，删除操作后直接清空
            // if (list.length == 1 && isdel) {
            if (list.length == 1) {

                this.setData({
                    currentList: whichList,
                    [whichList]: [],
                    [nomoreflag]: true
                })
                util.hideLoading()
                return
            }

            // this.setData({
            //     // currentIndex: isdel ? '' : this.data.currentIndex,
            //     currentIndex: 0,

            //     [nomoreflag]: true
            // })
            // util.hideLoading()
            // return
        }

        // 利用数组splice方法替换列表，起始索引通过计算获取，个数即是每页个数，替换内容为新请求的数据
        list.splice((pagenum - 1) * this.data.limit, limitnum, ...res)
        this.setData({
            currentList: whichList,
            [whichList]: list,
            currentIndex: isdel ? '' : this.data.currentIndex
        })
        util.hideLoading()
    },


    // 按类型请求订单填入对应数组
    async getOrderList() {

        // 如果后面做上拉加载 whichlist变量就需要加到data中保存
        // 选择对应的数组
        let whichList
        let pagenum
        let nomoreflag

        switch (this.data.status) {
            case '0':
                whichList = 'all_list';
                pagenum = ++this.data.allpage
                nomoreflag = 'nomoreall'
                this.setData({ allpage: pagenum })
                break;
            case '1':
                whichList = 'waitPay_list';
                pagenum = ++this.data.waitPpage
                nomoreflag = 'nomorep'
                this.setData({ waitPpage: pagenum })
                break;
            case '2':
                whichList = 'waitDeliver_list';
                pagenum = ++this.data.waitDpage
                nomoreflag = 'nomored'
                this.setData({ waitDpage: pagenum })
                break;
            case '3':
                whichList = 'waitReceive_list';
                pagenum = ++this.data.waitRpage
                nomoreflag = 'nomorer'
                this.setData({ waitRpage: pagenum })
                break;
            case '4':
                whichList = 'waitComment_list';
                pagenum = ++this.data.waitCpage
                nomoreflag = 'nomorec'
                this.setData({ waitCpage: pagenum })
                break;
            case '5':
                whichList = 'service_list';
                nomoreflag = 'nomores'
                pagenum = ++this.data.waitSpage
                this.setData({ waitSpage: pagenum })
                break;
            default:
                break;
        }

        // 请求前直接切换当前列表名，因为这个本就不受请求结果影响
        // 而且currentList用到地方挺多，必须保证切换后对应
        this.setData({
            currentList: whichList,
        })

        // 判断是否已经到底
        if (this.data[nomoreflag]) {
            // util.hideLoading()
            return
        }

        util.showLoading('正在加载')

        let params = {
            uid: this.data.uid,
            status: this.data.status,
            page: pagenum,
            limit: this.data.limit
        }

        // 如果为下拉刷新，重新开辟新数组填充数据
        let ispullrefresh = this.data.ispullrefresh

        let list = ispullrefresh ? [] : this.data[whichList]
        let res = await request.post(api.orderlist, params)
        // 如果是退款/售后 判断是否已退款，有展示对应退款金额
        if (whichList == 'service_list' || whichList == 'all_list') {
            for (let i = 0; i < res.length; i++) {
                if (res[i].status == 6) {
                    let RMresult = await request.postall(api.RMdetail, { oid: res[i].id })
                    if (RMresult.code == 0 && RMresult.data.pay_status == 2) {
                        res[i].RMamount = RMresult.data.amount
                    }
                }

            }
        }

        if (res.length == 0) {
            this.setData({
                [nomoreflag]: true
            })
            // 如果是下拉刷新 需要清空原列表
            if (ispullrefresh) {
                this.setData({
                    [whichList]: [],
                })
            }
            util.hideLoading()
            return true
        }
        let newlist = list.concat(res)

        this.setData({
            [whichList]: newlist,
        })
        util.hideLoading()
        return true
    },

    // 切换tab栏
    changing_tab(e) {
        this.tapNoSeemask()

        this.setData({
            currentIndex: '',
            chosen_index: e.currentTarget.dataset.index,
            status: `${e.currentTarget.dataset.index}`
        })

        // 切换tab后，上拉加载会检查底部，自动调用getOrderList
        // this.getOrderList()
    },

    // 前往订单详情
    go_order_detail(e) {
        let id = e.currentTarget.dataset.id
        let status = e.currentTarget.dataset.status

        let url = `/pages/order/order_detail?id=${id}&status=${status}`
        wx.navigateTo({
            url,
        })
    },

    // 滑动切换订单列表
    changing_swiper_item(e) {
        // if (true) e.preventDefault();

        // if (false) {
        this.setData({
            chosen_index: e.detail.current,
            status: `${e.detail.current}`
        })
        this.getOrderList()
        // }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})